Why `A & a = a` is valid?
Posted
by psaghelyi
on Stack Overflow
See other posts from Stack Overflow
or by psaghelyi
Published on 2010-04-13T21:01:19Z
Indexed on
2010/04/13
21:03 UTC
Read the original article
Hit count: 454
#include <iostream>
#include <assert.h>
using namespace std;
struct Base
{
Base() : m_member1(1) {}
Base(const Base & other)
{
assert(this != &other); // this should trigger
m_member1 = other.m_member1;
}
int m_member1;
};
struct Derived
{
Derived(Base & base) : m_base(m_base) {} // m_base(base)
Base & m_base;
};
void main()
{
Base base;
Derived derived(base);
cout << derived.m_base.m_member1 << endl; // crashes here
}
The above example is a synthesized version of a mistyped constructor.
I used reference at the class member Derived::m_base
because I wanted to make sure that the member will be initialized as the constructor had called.
One problem is that nor GCC nor MSVC gives me a warning at m_base(m_base)
. But the more serious for me is that the assert finds everything fine and the application crashes later (sometimes far away from the mistake). Question: Is there any way to indicate such mistakes?
© Stack Overflow or respective owner